<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>通讯录</title>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/materialdesignicons.min.css"/>
    <link href="js/jquery-confirm/jquery-confirm.min.css" rel="stylesheet">
    <link href="js/bootstrap-table/bootstrap-table.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container-fluid p-t-15">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-body">
                <form class="form-inline" name="searchForm" action="#" method="post">
                    <input
                            id="userId"
                            type="hidden"
                            name="userId"
                            value="0"
                            th:value="${session.user.id}"
                            class="form-control"
                    />

                    <label for="chatName" class="ml-2"></label>
                    <input
                            id="chatName"
                            type="text"
                            placeholder="名称"
                            name="chatName"
                            class="form-control"
                    />

                    <label for="chatType" class="ml-2"></label>
                    <select id="chatType" name="chatType" class="form-control">
                        <option value="0">全部</option>
                        <option value="1">好友</option>
                        <option value="2">群聊</option>
                    </select>

                    <input
                            type="button"
                            class="btn btn-primary ml-2"
                            value="查询"
                            onclick="search()"
                    />
                    <input
                            type="reset"
                            class="btn btn-secondary ml-2"
                            value="清空"
                            onclick="search()"
                    />
                </form>
                <div id="toolbar" class="toolbar-btn-action">
                    <input type="button" class="btn btn-primary ml-2" value="好友请求" onclick="showFriendRequests()"/>
                    <input type="button" class="btn btn-primary ml-2" value="添加好友" onclick="addFriend()"/>
                    <input type="button" class="btn btn-primary ml-2" value="创建群聊" onclick="createGroup()"/>
                </div>

                <table id="table"></table>
            </div>
        </div>
    </div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery-confirm/jquery-confirm.min.js"></script>

<script
        type="text/javascript"
        src="js/bootstrap-table/bootstrap-table.min.js"
></script>
<script
        type="text/javascript"
        src="js/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"
></script>
<script>
    $("#table").bootstrapTable({
        classes: "table border-bottom table-hover",
        url: "/chat/list",
        method: "get",
        dataType: "json", // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
        uniqueId: "id",
        idField: "id", // 每行的唯一标识字段
        toolbar: "#toolbar", // 工具按钮容器
        clickToSelect: true, // 是否启用点击选中行
        showColumns: true, // 是否显示所有的列
        showRefresh: true, // 是否显示刷新按钮
        showToggle: true, // 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)
        pagination: true, // 是否显示分页
        sortOrder: "asc", // 排序方式

        // 响应处理
        responseHandler: function (res) {
            return res.data;
        },

        // 查询参数
        queryParams: function () {
            return $("form:eq(0)").serializeArray();
        },

        sidePagination: "client", // 分页方式：client客户端分页，server服务端分页
        pageNumber: 1, // 初始化加载第一页，默认第一页
        pageSize: 6, // 每页的记录行数
        pageList: [3, 6, 9, 12], // 可供选择的每页的行数

        columns: [
            {
                field: "example",
                checkbox: true, // 是否显示复选框
            },
            {
                field: 'chatId',
                visible: false
            },
            {
                field: 'no',
                align: 'center',
                title: '序号',
                formatter: function (value, row, index) {
                    //返回序号，注意index是从0开始的，所以要加上1
                    return index + 1;
                }
            },
            {
                field: "avatar",
                align: "center",
                title: "头像",
                formatter: function (value, row, index) {
                    return '<img src="' + value + '" width="40px" height="40px" />';
                }
            },
            {
                field: "name",
                align: "center",
                title: "名称(备注)",
                formatter: function (value, row, index) {
                    if (row.remark) {
                        return `${value}(${row.remark})`;
                    }

                    return value;
                }
            },
            {
                field: "type",
                align: "center",
                title: "类型",
                formatter: function (value, row, index) {
                    var value = "";
                    if (row.type == 1) {
                        value = '<span class="badge badge-primary">好友</span>';
                    } else if (row.type == 2) {
                        value = '<span class="badge badge-success">群聊</span>';
                    } else {
                        value = "-";
                    }
                    return value;
                },
            },
            {
                field: "description",
                align: "center",
                title: "介绍",
            },
            {
                field: "operate",
                align: "center",
                title: "操作",
                formatter: btnGroup, // 自定义方法
                events: {
                    "click .chat-btn": function (event, value, row, index) {
                        onChat(row);
                    },
                    "click .detail-btn": function (event, value, row, index) {
                        onDetail(row);
                    },
                    "click .top-btn": function (event, value, row, index) {
                        onTop(row);
                    },
                    "click .clean-btn": function (event, value, row, index) {
                        onClean(row);
                    },
                    "click .invite-btn": function (event, value, row, index) {
                        onInvite(row);
                    },
                },
            },
        ],
    });

    // 操作按钮
    function btnGroup(value, row, index) {
        let html =
            '<a href="#" class="btn btn-xs btn-primary mr-2 chat-btn" title="聊天" >聊天</a>' +
            '<a href="#" class="btn btn-xs btn-warning mr-2 top-btn" title="置顶">置顶</a>' +
            '<a href="#" class="btn btn-xs btn-success mr-2 detail-btn" title="详情" >详情</a>' +
            '<a href="#" class="btn btn-xs btn-danger mr-2 clean-btn" title="清空聊天记录">清空聊天</a>';

        if (row.type == 2) {
            html += '<a href="#" class="btn btn-xs btn-primary mr-2 invite-btn" title="邀请好友">邀请好友</a>';
        }

        return html;
    }

    // 操作方法 - 聊天
    function onChat(row) {
        window.location.href = "/content?chatId=" + row.chatId;
    }

    // 操作方法 - 详情
    function onDetail(row) {
        window.location.href = "/detail/" + row.chatId;
    }

    // 操作方法 - 置顶
    function onTop(row) {
        console.log('置顶', row);
    }

    // 操作方法 - 清空聊天
    function onClean(row) {
        $.confirm({
            title: '删除',
            content: '您确定要将' + row.name + '聊天记录清空吗？',
            type: 'red',
            icon: 'mdi mdi-close',
            typeAnimated: true,
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-red',
                    action: function () {
                        let chatId = row.chatId;
                        if (row.chatId.indexOf("user") !== -1) {
                            chatId = formatChatId(chatId + "-" + [[${session.user.id}]])
                        }
                        $.get("/chat/clean/" + chatId, function (data) {
                            if (data.code === 200) {
                                $.alert({
                                    title: '成功',
                                    content: data.message,
                                    type: 'green',
                                    icon: 'mdi mdi-close',
                                    typeAnimated: true,
                                })
                            } else {
                                $.alert({
                                    title: '失败',
                                    content: data.message,
                                    type: 'red',
                                    icon: 'mdi mdi-close',
                                    typeAnimated: true,
                                });
                            }
                        });
                    }
                },
                cancel: { // 取消按钮
                    text: '取消',
                    action: function () {
                    }
                }
            }
        });
    }

    // 操作方法 - 查询
    function search() {
        $("#table").bootstrapTable("refresh");
    }

    function formatChatId(chatId) {
        if (chatId != null && chatId.indexOf("user") !== -1) {
            const arr = chatId.split("-").slice(1)
            const sender = arr[0]
            const receiver = arr[1]

            if (sender < receiver) {
                return `user-${sender}-${receiver}`;
            } else {
                return `user-${receiver}-${sender}`;
            }
        } else {
            return chatId;
        }
    }

    // 添加好友
    function addFriend() {
        $.confirm({
            title: '添加好友',
            content: `
            <form id="addFriendForm" class="form-horizontal">
                <div class="form-group">
                    <label class="col-form-label">好友ID/用户名:</label>
                    <input type="text" id="friendId" class="form-control" placeholder="输入好友ID或用户名" required>
                </div>
                <div class="form-group">
                    <label class="col-form-label">验证消息:</label>
                    <textarea id="verifyMsg" class="form-control" placeholder="可选"></textarea>
                </div>
            </form>
        `,
            type: 'blue',
            buttons: {
                confirm: {
                    text: '发送请求',
                    btnClass: 'btn-primary',
                    action: function () {
                        const friendInfo = $('#friendId').val();
                        const verifyMsg = $('#verifyMsg').val();

                        if (!friendInfo) {
                            $.alert('请输入好友ID或用户名！');
                            return false;
                        }

                        // 调用后端 API
                        $.post('/friend/add', {
                            friendInfo: friendInfo,
                            verifyMsg: verifyMsg || '我想添加你为好友'
                        }, function (data) {
                            if (data.code === 200) {
                                $.alert({
                                    title: '成功',
                                    content: '好友请求已发送！',
                                    type: 'green'
                                });
                            } else {
                                $.alert({
                                    title: '失败',
                                    content: data.message || '添加好友失败',
                                    type: 'red'
                                });
                            }
                        }).fail(function () {
                            $.alert('服务器错误，请稍后重试！');
                        });
                    }
                },
                cancel: {
                    text: '取消'
                }
            }
        });
    }

    // 创建群聊
    function createGroup() {
        $.confirm({
            title: '创建群聊',
            content: `
            <form id="createGroupForm" class="form-horizontal">
                <div class="form-group">
                    <label class="col-form-label">群聊名称:</label>
                    <input type="text" id="groupName" class="form-control" placeholder="输入群聊名称" required>
                </div>
                <div class="form-group">
                    <label class="col-form-label">群聊描述:</label>
                    <textarea id="groupDesc" class="form-control" placeholder="可选"></textarea>
                </div>
                <div class="form-group">
                    <label class="col-form-label">群聊备注:</label>
                    <textarea id="groupRemark" class="form-control" placeholder="可选"></textarea>
                </div>
            </form>
        `,
            type: 'blue',
            buttons: {
                confirm: {
                    text: '创建',
                    btnClass: 'btn-primary',
                    action: function () {
                        const groupName = $('#groupName').val();
                        const groupDesc = $('#groupDesc').val();
                        const groupRemark = $('#groupRemark').val();

                        if (!groupName) {
                            $.alert('请输入群聊名称！');
                            return false;
                        }

                        // 调用后端 API
                        $.post('/group/create', {
                            name: groupName,
                            description: groupDesc || '暂无描述',
                            remark: groupRemark,
                        }, function (data) {
                            if (data.code === 200) {
                                $.alert({
                                    title: '成功',
                                    content: '群聊创建成功！',
                                    type: 'green'
                                });
                                // 刷新列表
                                $("#table").bootstrapTable("refresh");
                            } else {
                                $.alert({
                                    title: '失败',
                                    content: data.message || '创建群聊失败',
                                    type: 'red'
                                });
                            }
                        }).fail(function () {
                            $.alert('服务器错误，请稍后重试！');
                        });
                    }
                },
                cancel: {
                    text: '取消'
                }
            }
        });
    }

    // 查询好友请求
    let friendRequestDialog = null;
    function showFriendRequests() {
        if (friendRequestDialog) {
            friendRequestDialog.close();
        }

        $.ajax({
            url: '/friend/requests',
            type: 'get',
            beforeSend: function () {
                // 显示加载状态
                $('.jconfirm-content').html('<div class="text-center p-3"><i class="mdi mdi-loading mdi-spin"></i> 加载中...</div>');
            },
            success: function (data) {
                let html;
                if (data.code === 200 && data.data.length > 0) {
                    html = '<table id="friendRequestsTable" class="table">' +
                        '<tr><th>申请人</th><th>验证消息</th><th>操作</th></tr>';

                    data.data.forEach(request => {
                        let btn;
                        if (request.status === 1) {
                            btn = '<span class="text-success">已同意</span>'
                        } else if (request.status === 2) {
                            btn = '<span class="text-danger">已拒绝</span>'
                        } else {
                            btn = `<button onclick="handleFriendRequest(${request.id}, 1)"
                                        class="btn btn-sm btn-success">同意</button>
                                <button onclick="handleFriendRequest(${request.id}, 2)"
                                        class="btn btn-sm btn-danger">拒绝</button>`
                        }

                        html += `
                        <tr data-request-id="${request.id}">
                            <td>${request.senderName}</td>
                            <td>${request.verifyMsg || '无'}</td>
                            <td>${btn}</td>
                        </tr>
                    `;
                    });
                    html += '</table>';
                } else {
                    html = '<div class="text-center p-3">暂无好友请求</div>';
                }

                friendRequestDialog = $.confirm({
                    title: '好友请求',
                    content: html,
                    type: 'blue',
                    buttons: {close: {text: '关闭'}},
                    onClose: function () {
                        // 刷新好友列表
                        $("#table").bootstrapTable("refresh");
                    }
                });
            }
        });
    }

    // 处理同意/拒绝请求
    function handleFriendRequest(requestId, status) {
        // 禁用按钮并显示加载状态
        const $btn = $(`button[onclick*="${requestId}"]`);
        $btn.prop('disabled', true).html('<i class="mdi mdi-loading mdi-spin"></i> 处理中...');

        $.post('/friend/respond', {
            requestId: requestId,
            status: status
        }, function (data) {
            if (data.code === 200) {
                $.alert({
                    title: '成功',
                    content: status === 1 ? '已同意好友请求' : '已拒绝请求',
                    type: 'green',
                    onClose: function () {
                        showFriendRequests(); // 重新加载请求列表
                    }
                });
            } else {
                // 恢复按钮状态
                $btn.prop('disabled', false).html(status === 1 ? '同意' : '拒绝');
                $.alert({
                    title: '失败',
                    content: data.message,
                    type: 'red'
                });
            }
        }).fail(function () {
            $btn.prop('disabled', false).html(status === 1 ? '同意' : '拒绝');
        });
    }

    // 邀请好友
    let inviteDialog = null;
    function onInvite(row) {

        if (inviteDialog) {
            inviteDialog.close();
        }

        $.get(`/group/members/${row.chatId}`, function (res) {
            $.ajax({
                url: '/user/friends',
                type: 'get',
                beforeSend: function () {
                    // 显示加载状态
                    $('.jconfirm-content').html('<div class="text-center p-3"><i class="mdi mdi-loading mdi-spin"></i> 加载中...</div>');
                },
                success: function (data) {
                    let html;
                    if (data.code === 200 && data.data.length > 0) {
                        html = '<table id="friendRequestsTable" class="table">' +
                            '<tr><th>名称</th><th>性别</th><th>操作</th></tr>';

                        data.data.forEach(request => {
                            let btn;
                            if(!res.data.includes(request.id)){
                                btn = `<button onclick="handleInvite('${row.chatId}', ${request.id})"
                                        class="btn btn-sm btn-success">邀请</button>`
                            }else {
                                btn = '<span class="text-success">已加入</span>'
                            }

                            html += `
                        <tr data-request-id="${request.id}">
                            <td>${request.realName}</td>
                            <td>${request.gender === '1' ? '男' : request.gender === '2' ? '女' : '保密'}</td>
                            <td>${btn}</td>
                        </tr>
                    `;
                        });
                        html += '</table>';
                    } else {
                        html = '<div class="text-center p-3">暂无好友</div>';
                    }

                    inviteDialog = $.confirm({
                        title: '邀请好友',
                        content: html,
                        type: 'blue',
                        buttons: {close: {text: '关闭'}},
                    });
                }
            });
        })
    }

    // 邀请
    function handleInvite(chatId, friendId) {
        // 禁用按钮并显示加载状态
        const $btn = $(`button[onclick*="${friendId}"]`);
        $btn.prop('disabled', true).html('<i class="mdi mdi-loading mdi-spin"></i> 邀请中...');

        $.post('/group/addMember', {
            chatId: chatId,
            friendId: friendId,
        }, function (data) {
            if (data.code === 200) {
                $.alert({
                    title: '成功',
                    content: '邀请成功',
                    type: 'green',
                    onClose: function () {
                        onInvite({chatId: chatId})
                    }
                })
            } else {
                // // 恢复按钮状态
                $btn.prop('disabled', false).html('邀请');
                $.alert({
                    title: '失败',
                    content: data.message,
                    type: 'red'
                });
            }
        }).fail(function () {
            $btn.prop('disabled', false).html('邀请');
        });
    }

</script>
</body>
</html>
